﻿using System;
using System.Data;
using System.Web.Security;
using Token.Piker.BLL;
using Token.Piker.Common;

namespace Token.Piker.Web
{
    public partial class Login : System.Web.UI.Page
    {
        static int errorCount=0;//用于记录登录失败的次数

        protected void Page_Load(object sender, EventArgs e)
        {
            if (errorCount < 3)
            {
                p_ValidateCode.Visible = false;
            }
            else
            {
                p_ValidateCode.Visible = true;
            }

            if (p_Tip.Visible == true)
            {
                p_Tip.Visible =false;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (this.txtValidateCode.Text.Trim() != string.Empty)
            {
                //验证验证码
                if (string.Compare(Session["UserValidateCode"].ToString(), this.txtValidateCode.Text.Trim(), true) != 0)
                {
                    lblValidateCodeTip.Visible = true;
                    lblValidateCodeTip.Text = "验证码不正确";
                    return;
                }
            }

            string username = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text.Trim();

            if (CheckLogin(username, password) == true)
            {
                //重定向
                Response.Redirect("Default.aspx");
            }
            else
            {
                p_Tip.Visible = true;

                if (errorCount == 2)
                {
                    lblTip.Text = "你已经累计错误三次，请输入验证码";
                    p_ValidateCode.Visible = true;
                }
                else
                {
                    lblTip.Text = "用户名或密码不正确";
                }

                errorCount++;
            }
        }

        private bool CheckLogin(string username, string password)
        {
            string encodedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            UserBLL userBLL = new UserBLL();
            string strWhere = "UserName = '" + username + "' AND UserPwd = '" + encodedPassword + "'";
            DataSet ds = userBLL.GetList(strWhere);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                string userId = dr["ID"].ToString();
                string userName = dr["UserName"].ToString();
                Session[GlobalConstants.PIKER_USER_ID] = userId;
                Session[GlobalConstants.PIKER_USER_NAME] = userName;
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}